package com.wanwu.channel.notify.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wanwu.channel.notify.biz.mapper.PayNotifyMapper;
import com.wanwu.channel.notify.biz.mapper.TradeOrderMapper;
import com.wanwu.channel.notify.biz.po.TradeOrder;
import com.wanwu.channel.notify.constants.CommonConstants;
import com.wanwu.channel.notify.model.DeliveryNotifyReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class TradeOrderDeliveryService {
    @Autowired
    private TradeOrderMapper tradeOrderMapper;
    @Autowired
    private PayNotifyMapper payNotifyMapper;

    /**
     * 获取交易单
     * @param outTradeNo
     */
    public TradeOrder getTradeOrder(String outTradeNo){
        LambdaQueryWrapper<TradeOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TradeOrder::getOutTradeNo,outTradeNo);
        return tradeOrderMapper.selectOne(queryWrapper);
    }

    /**
     * 更新收货状态
     * @param tradeOrder
     * @param deliveryState
     */
    private void updateTradeOrder(TradeOrder tradeOrder,Integer deliveryState){

        tradeOrder.setStatus(CommonConstants.TRADE_STATUS_FINISH);//交易完成
        //处理回调结果
        if (CommonConstants.TRADE_PAY_NOTIFY_RESULT_SUCCESS.equals(deliveryState)) {
            //成功处理
            tradeOrder.setResult(CommonConstants.TRADE_DELIVERY_RESULT_SUCCESS);//收货成功
            tradeOrder.setUpdateTime(new Date());
        } else {
            //失败处理
            tradeOrder.setResult(CommonConstants.TRADE_DELIVERY_RESULT_FAIL);
        }
        tradeOrderMapper.updateById(tradeOrder);
    }



    /**
     * 确认收货状态
     * @param deliveryNotifyReq
     * @throws Exception
     */
    public void syncPayStatus(DeliveryNotifyReq deliveryNotifyReq) throws Exception {
        TradeOrder tradeOrder = getTradeOrder(deliveryNotifyReq.getOutTradeNo());
        if(Objects.isNull(tradeOrder)){
            throw new Exception("订单号不存在");
        }
        if(!CommonConstants.TRADE_RESULT_INIT.equals(tradeOrder.getResult())){
            throw new Exception("交易订单已完成");
        }
        if(!CommonConstants.TRADE_TYRPE_GUARANTEE.equals(tradeOrder.getType())){
            throw new Exception("非担保交易无需收货通知");
        }
        updateTradeOrder(tradeOrder, deliveryNotifyReq.getDeliveryResult());
    }



}

